package storage

import (
	"encoding/json"
	"io/ioutil"
	"os"
	"time"
)

var devicesFile = "devices.json"
var configFile = "config.json"

func LoadDevices() ([]Device, error) {
	file, err := ioutil.ReadFile(devicesFile)
	if err != nil {
		if os.IsNotExist(err) {
			return []Device{}, nil
		}
		return nil, err
	}

	var devices []Device
	err = json.Unmarshal(file, &devices)
	if err != nil {
		return nil, err
	}

	return devices, nil
}

func SaveDevices(devices []Device) error {
	file, err := json.MarshalIndent(devices, "", "  ")
	if err != nil {
		return err
	}

	return ioutil.WriteFile(devicesFile, file, 0644)
}

func LoadConfig() (Config, error) {
	file, err := ioutil.ReadFile(configFile)
	if err != nil {
		if os.IsNotExist(err) {
			return Config{}, nil
		}
		return Config{}, err
	}

	var config Config
	err = json.Unmarshal(file, &config)
	if err != nil {
		return Config{}, err
	}

	return config, nil
}

func SaveConfig(config Config) error {
	file, err := json.MarshalIndent(config, "", "  ")
	if err != nil {
		return err
	}

	return ioutil.WriteFile(configFile, file, 0644)
}

func UpdateDeviceLastActive(id int) error {
	devices, err := LoadDevices()
	if err != nil {
		return err
	}

	for i, device := range devices {
		if device.ID == id {
			devices[i].LastActive = time.Now().Format(time.RFC3339)
			break
		}
	}

	return SaveDevices(devices)
}
